<?php


namespace app\index\controller;


use app\common\Base;
use app\index\model\Business;
use app\index\model\Commodity;
use app\index\model\CommodityAppraises;
use app\index\model\Favorites;
use app\index\model\Order;
use app\index\model\Region;
use think\Exception;
use think\Request;

class Search extends Base
{

    //猜你喜欢(成功）

    public function  youLike(Business $business,CommodityAppraises $commodityAppraises, Commodity $commodity,Order $order ){
        // 请加上try catch
        //喜欢随机出来
        try {
            if (!$data = json_decode($business->randBusiness('id,businessName,businessImg,county'),true)) {
                return responseJson(Base::FAIL,'数据获取失败,请重试');
            }
            if (empty($data)){
                return responseJson(Base::FAIL,'暂无数据');
            }
            if (count($data) < 6){
                $businessData = $data;
            }else{
                $arr = array_rand($data,3);
                shuffle($arr);
                $businessData = [];
                foreach ($arr as $value){
                    array_push($businessData,$data[$value]);
                }
            }
            foreach ($businessData as $i => $val){
                //五星评价
                $businessData[$i]['Evaluation'] = ceil(($commodityAppraises->commodityScore($businessData[$i]['id']) + $commodityAppraises->serviceScore($businessData[$i]['id']) + $commodityAppraises->timeScore($businessData[$i]['id']))/3);
              $county = json_decode($business->youLikecounty($businessData[$i]['id'] ,true));
                    //人均
                foreach ($county[0] as $key=>$value){
                    $businessData[$i]['county']=  $value;
                }

                $businessData[$i]['perCapita'] = number_format($order->avgBusiness($businessData[$i]['id']),1);
            }
            return responseJson(Base::OK,'数据获取成功',$businessData);
        }catch (Exception $e){
            throw $e;
        }
    }



    //搜索结果(搜索成功）（分页 成功）
    public  function  searchBusiness(Request $request , Business $business , CommodityAppraises $commodityAppraises,Order $order, Favorites $favorites){
        // TODO 将获取缓存信息放在中间件里，请加上try catch
        $arr = $request->cacheInfo;
        $userId = $arr['id'];//获取用户id

        $pagenum = $request->post('pagenum');//获取当前页数

        $input = $request->post('input');//获取输入框的值
        $sort = $request->post('sort');//获取排序的值
        $min = $request->post('min');//获取人均输入框的值
        $max = $request->post('max');//获取人均输入框的值
        $place = $request->post('place');//获取地区筛选
        try{
            if($sort ==''){
                $sort = 'desc';
            }else{
                $sort = '';
            }
            if($pagenum ==''){
                $pagenum = 1;
            }
            $favoritestext = $favorites->findFavoritesid($userId);//获取收藏店铺
           
            $favoritesid = array();
            // TODO 善用内置方法，不需要使用循环
            for($e=0;$e<count($favoritestext);$e++){
                array_push($favoritesid,$favoritestext[$e]['businessId']);
            }
            if($input ==''){
                return responseJson(Base::FAIL,'空？');
            }

            if($place==''){
                $businessData = json_decode($business->searchBusiness($input,$sort),true);
            }else{
                $businessData =json_decode( $business->searchBusinessplace($input,$sort,$place),true);
            }

            //评分
            foreach ($businessData as $i => $val){
                //五星评价
                $businessData[$i]['Evaluation'] = ceil(($commodityAppraises->commodityScore($businessData[$i]['id']) + $commodityAppraises->serviceScore($businessData[$i]['id']) + $commodityAppraises->timeScore($businessData[$i]['id']))/3);
                //人均
                $businessData[$i]['perCapita'] = number_format($order->avgBusiness($businessData[$i]['id']),1);
            }
            //每页起始键                   定义分页数据条数
            $start = $pagenum  * Base::$pageSize - Base::$pageSize;
            //每页结尾键
            $end = $pagenum * Base::$pageSize;

            //循环出指定键
//            return print_r($businessData);

            //判断该用户是否收藏此用户‘
            for($w=0;$w<count($businessData);$w++){
                $bid = $businessData[$w]['id'];
                $businessData[$w]['isfavorites']=0;
                if (in_array($bid,$favoritesid)){
                    $businessData[$w]['isfavorites']=1;
                }

            }

            $data=array();
            $Data=array();
            $zong =array();
            //人均区间
            // TODO 若$min,$max的值不是'' 是null，那么这里会报错吗？
            if($min == null){
                $min='';
            }
            if($max ==null){
                $max ='';
            }
            if ($min == '' && $max == ''){
                if($end > count($businessData)){
                    $end = count($businessData);
                }
                $page =intdiv(count($businessData),5) + 1 ;
                //添加总页数，和当前页数
                $array = ['page' =>$page,'pagenum' =>$pagenum];


                for ($ii = $start;$ii<$end;$ii++){
                    array_push($Data, $businessData[$ii]);
                }
                $zong['page'] =$array;
                $zong['shuju'] =$Data;
                return responseJson(Base::OK,'成功',$zong);
            }

            //最高价格
            if($min == '' ){
                for($i = 0 ;$i<count($businessData);$i++){
                    $perCapita = $businessData[$i]['perCapita'];
                    if($perCapita <= $max){
                        array_push($data, $businessData[$i]);
                    }
                }
                //如果操过了，就按数量最后
                if($end > count($data)){
                    $end = count($data);
                }
                $page =intdiv(count($data),5) + 1 ;
                //添加总页数，和当前页数
                $array = ['page' =>$page,'pagenum' =>$pagenum];


                for ($ii = $start;$ii<$end;$ii++){
                    array_push($Data, $businessData[$ii]);
                }
                $zong['page'] =$array;
                $zong['shuju'] =$Data;
                return responseJson(Base::OK,$place.'成功最高'.$max,$zong);
            }
            //最低价格
            if($max == '' ){
                for($i = 0 ;$i<count($businessData);$i++){
                    $perCapita = $businessData[$i]['perCapita'];
                    if($perCapita >= $min){
                        array_push($data, $businessData[$i]);
                    }
                }
                //如果操过了，就按数量最后
                if($end > count($data)){
                    $end = count($data);
                }
                $page =intdiv(count($data),5) + 1 ;
                //添加总页数，和当前页数
                $array = ['page' =>$page,'pagenum' =>$pagenum];


                for ($ii = $start;$ii<$end;$ii++){
                    array_push($Data, $businessData[$ii]);
                }
                $zong['page'] =$array;
                $zong['shuju'] =$Data;
                return responseJson(Base::OK,$place.'成功最低'.$min,$zong);
            }
            //区间价格

            for($i = 0 ;$i<count($businessData);$i++){
                $perCapita = $businessData[$i]['perCapita'];
                if($perCapita >= $min && $perCapita <= $max){
                    array_push($data, $businessData[$i]);
                }
            }
            //如果操过了，就按数量最后
            if($end > count($data)){
                $end = count($data);
            }
            $page =intdiv(count($data),5) + 1 ;
            //添加总页数，和当前页数
            $array = ['page' =>$page,'pagenum' =>$pagenum];

            // TODO 以确保$end数组的元素数量一定等于$businessData这个数组？
            for ($ii = $start;$ii<$end;$ii++){
                array_push($Data, $businessData[$ii]);
            }
            $zong['page'] =$array;
            $zong['shuju'] =$Data;
            return responseJson(Base::OK,$place.'成功最高'.$max.'最低'.$min,$zong);
        }catch (Exception $e){
            throw  $e;
        }
        
    }
//加入收藏 （成功）
    public function  insertFavorites(Request $request,Favorites $favorites){
        $bid =  $request->post('businessid');//获取商家id
        // TODO 将获取缓存信息放在中间件里
        $arr = $request->cacheInfo;
        $userId = $arr['id'];//获取用户id
        if ($favorites->insertFavorites($userId,$bid)){
            return responseJson(Base::OK,'添加成功');
        }
    }
    //删除收藏 （成功）
    public function  delFavorites(Request $request,Favorites $favorites){
        $bid =  $request->post('businessid');//获取商家id
        // TODO 将获取缓存信息放在中间件里
        $arr = $request->cacheInfo;
        $userId = $arr['id'];//获取用户id
        if ($favorites->delFavorites($userId,$bid)){
            return responseJson(Base::OK,'删除成功');
        }
    }
    //地区
    public function  add(Request $request ,Region $region){
        // 代码缩进不规范，请使用try catch
       $code = $request ->post('code');//获取地区城市code
        $data  = $region->selcounty($code);
        return responseJson(Base::OK,'列出成功', $data);
    }
    public function  inputSearch(Request $request ,Business $business){
       $input = $request ->post('input');//获取input
        $q = 10;
        $data=array();
       $business = $business->searchBusiness($input,0);
       // TODO 为什么还需要count一下数量，循环方法只有一种吗？
       if($q>count($business)){
           $q=count($business);
       }
        for($i=0;$i<$q;$i++){
            array_push($data,$business[$i]['businessName']);
        }
        return responseJson(Base::OK,'列出成功', $data);
    }
}